﻿Ext.define('SmartClient.controller.LoginController',
   {
      extend: 'Deft.mvc.ViewController',
      inject: ['loginStore'],

      init: function()
      {
         this.getLoginButton().addListener('click', this.login, this);
         this.getUserLoginField().addListener('keyup', this.loginOnPressEnter, this);
         this.getUserPasswordField().addListener('keyup', this.loginOnPressEnter, this);
         return this.callParent(arguments);
      },

      // Element IDs here
      // DeftJS will create a getter and setter for property
      control:
         {
            loginButton: true,
            userLoginField: true,
            userPasswordField: true
         },

      config:
         {
            // Ext JS will create a getter and setter for property
            loginStore: null
         },

      login: function()
      {
         var login = this.getUserLoginField().getValue(),
             password = this.getUserPasswordField().getValue();

         if (login)
         {
            this.getLoginStore().load(
            {
               params:
                  {
                     login: login,
                     password: password
                  },
               scope: this,
               callback: function (records, operation, success)
               {
                  this.getView().close();
                  //var type = records[0].raw.userData.type;
                  var type = SmartClient.Application.TECHNOLOGIST_USER;
                  if (type === SmartClient.Application.CUSTOMER_USER)
                  {
                     SmartClient.utils.CookieUtils.setCookie(SmartClient.Application.USER_TYPE_COOKIE, SmartClient.Application.CUSTOMER_USER, 30);
                     SmartClient.utils.CookieUtils.setCookie(SmartClient.Application.USER_COOKIE, login, 30);
                     Ext.create('SmartClient.view.Viewport');
                  }
                  else if (type === SmartClient.Application.TECHNOLOGIST_USER)
                  {
                     SmartClient.utils.CookieUtils.setCookie(SmartClient.Application.USER_TYPE_COOKIE, SmartClient.Application.TECHNOLOGIST_USER, 30);
                     SmartClient.utils.CookieUtils.setCookie(SmartClient.Application.USER_COOKIE, login, 30);
                     Ext.create('SmartClient.view.SearchOrdersView');
                  }
               }
            });
         }
      },

      loginOnPressEnter: function (form, event)
      {
         if ((event.getKey() == 13) && !this.getLoginButton().isDisabled())
         {
            this.login();
         }
      }
   });